package com.tulele.vtool.service.impl;

import com.google.common.collect.Lists;
import com.tulele.vtool.exception.ServiceException;
import com.tulele.vtool.mapper.BrandInfoMapper;
import com.tulele.vtool.mapper.UserBrandInfoMapper;
import com.tulele.vtool.model.BrandInfo;
import com.tulele.vtool.model.LookArticleInfo;
import com.tulele.vtool.model.UserBrandInfo;
import com.tulele.vtool.model.combinedEntity.UserBrandCombinedInfo;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.ILookArticleInfoService;
import com.tulele.vtool.service.IUserBrandInfoService;
import com.tulele.vtool.service.IUserRelateArticleTypeInfoService;
import com.tulele.vtool.task.async.AddUserPlatformCommodityAsyncTask;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.RedisCacheUtil;
import io.micrometer.core.instrument.util.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserBrandInfoServiceImpl implements IUserBrandInfoService {

    @Autowired
    private UserBrandInfoMapper userBrandInfoMapper;

    @Autowired
    private AddUserPlatformCommodityAsyncTask addUserPlatformCommodityAsyncTask;

    @Autowired
    private BrandInfoMapper brandInfoMapper;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private IUserRelateArticleTypeInfoService iUserRelateArticleTypeInfoService;

    @Autowired
    private ILookArticleInfoService iLookArticleInfoService;

    @Override
    public int addUserBrandInfo(Integer userId,
                                Integer brandId,
                                Integer brandStatus,
                                Integer effectiveStatus,
                                Date createTime,
                                Integer indexNum) {
        UserBrandInfo addBrandInfo = new UserBrandInfo();
        addBrandInfo.setUserId(userId);
        addBrandInfo.setBrandId(brandId);
        addBrandInfo.setBrandStatus(brandStatus);
        addBrandInfo.setEffectiveStatus(effectiveStatus);
        addBrandInfo.setCreateTime(new Date());
        addBrandInfo.setIndexNum(indexNum);
        return userBrandInfoMapper.addUserBrandInfo(addBrandInfo);
    }

    @Override
    public List<String> getUserBrandNameInfo(Integer userId) {
        return userBrandInfoMapper.queryUserBrandName(userId);
    }

    @Override
    public List<UserBrandCombinedInfo> getUserBrandInfo(Integer userId) {
        return userBrandInfoMapper.queryUserBrandInfo(userId);
    }

    @Override
    public List<UserBrandCombinedInfo> getUserBrandInfo2(Integer userId) {
        return userBrandInfoMapper.queryUserBrandInfo2(userId);
    }

    @Override
    public int storeUserSubBrand(Integer userId, String brandId) {

        //先将用户当前所有品牌设置为无效
        userBrandInfoMapper.updateUserBrandEffectiveStatus(userId);

        String []branIds = brandId.split(",");

        List<String> brandIdsArr = Lists.newArrayList();
            Arrays.stream(branIds).forEach(b ->{
                brandIdsArr.add(b);

                // 通过品牌ID查询品牌绑定的品牌id信息
                String brandBindingIds = brandInfoMapper.queryBrandBindingIdsByBrandId(Integer.valueOf(b));
                if(StringUtils.isNotBlank(brandBindingIds)) {
                    String[] brandBindings = brandBindingIds.split(",");

                    for (String brandBindingId : brandBindings) {
                        if (!Arrays.asList(branIds).contains(brandBindingId)){
                            brandIdsArr.add(brandBindingId);
                        }
                    }
                }

//                // 20200703 yl 关注 哇哈哈秒眠 将默认关注 国药小红丸
//                if (branIds.length < 5 && b.equalsIgnoreCase("10839") && !Arrays.asList(branIds).contains("11638")){
//                    brandIdsArr.add("11638");
//                }
//
//                // 20210106 hyl 关注 秘乐 将默认关注 拍呱呱
//                if (branIds.length < 5 && b.equalsIgnoreCase("10938") && !Arrays.asList(branIds).contains("35915")){
//                    brandIdsArr.add("35915");
//                }
//
//                // 20210106 hyl 关注 supreme潮瘦 将默认关注 和之梦集团
//                if (branIds.length < 5 && b.equalsIgnoreCase("11407") && !Arrays.asList(branIds).contains("25208")){
//                    brandIdsArr.add("25208");
//                }
            });
        // 20200703 end 关注 哇哈哈秒眠 将默认关注 国药小红丸
        Integer index=0;
        for (String brandIdInfo : brandIdsArr) {
            Integer brandIdInt = Integer.valueOf(brandIdInfo);

            //查询用户对当前品牌的设置情况
            UserBrandInfo queryInfo = new UserBrandInfo();
            queryInfo.setUserId(userId);
            queryInfo.setBrandId(brandIdInt);
            UserBrandInfo brandStatusInfo = userBrandInfoMapper.queryUserBrandStatusInfo(queryInfo);

            //如果不存在，则直接添加
            if (brandStatusInfo == null) {
                UserBrandInfo addBrandInfo = new UserBrandInfo();
                addBrandInfo.setBrandId(brandIdInt);
                addBrandInfo.setUserId(userId);
                addBrandInfo.setBrandStatus(0);
                addBrandInfo.setEffectiveStatus(1);
                addBrandInfo.setCreateTime(new Date());
                addBrandInfo.setIndexNum(index);
                userBrandInfoMapper.addUserBrandInfo(addBrandInfo);
            } else {
                //如果品牌为无效状态，则进行修改
                int effectiveStatus = Optional.ofNullable(brandStatusInfo.getEffectiveStatus()).orElse(0);
                if (effectiveStatus == 0) {
                    UserBrandInfo updateBrandInfo = new UserBrandInfo();
                    updateBrandInfo.setId(brandStatusInfo.getId());
                    updateBrandInfo.setEffectiveStatus(1);
                    //updateBrandInfo.setCreateTime(new Date());
                    updateBrandInfo.setModifyTime(new Date());
                    updateBrandInfo.setIndexNum(index);
                    userBrandInfoMapper.updateUserBrandInfo(updateBrandInfo);
                }

            }
            index++;
        }

        processUserBrandSelectStatus(userId);

        return 0;
    }

    @Override
    public int updateUserBrandInfo(UserBrandInfo record){
        return userBrandInfoMapper.updateUserBrandInfo(record);
    }

    @Override
    public int switchUserMicroStation(Integer userId, Integer brandId) {

        userBrandInfoMapper.updateAllUserBrandStatus(userId);

        UserBrandInfo userBrandInfo = new UserBrandInfo();
        userBrandInfo.setUserId(userId);
        userBrandInfo.setBrandId(brandId);
        userBrandInfoMapper.updateUserSpecialBrandStatus(userBrandInfo);

        processUserBrandSelectStatus(userId);

        return 0;
    }

    @Override
    public int storeUserSettedBrand(Integer userId, String brandId) {

        //先将用户当前所有品牌设置为无效
        //userBrandInfoMapper.updateUserBrandEffectiveStatus(userId);

        String []branIds = brandId.split(",");

        for (String brandIdInfo : branIds) {
            Integer brandIdInt = Integer.valueOf(brandIdInfo);

            //查询用户对当前品牌的设置情况
            UserBrandInfo queryInfo = new UserBrandInfo();
            queryInfo.setUserId(userId);
            queryInfo.setBrandId(brandIdInt);
            UserBrandInfo brandStatusInfo = userBrandInfoMapper.queryUserBrandStatusInfo(queryInfo);

            //如果不存在，则直接添加
            if (brandStatusInfo == null) {
                UserBrandInfo addBrandInfo = new UserBrandInfo();
                addBrandInfo.setBrandId(brandIdInt);
                addBrandInfo.setUserId(userId);
                addBrandInfo.setBrandStatus(0);
                addBrandInfo.setEffectiveStatus(1);
                addBrandInfo.setModifyTime(DateUtil.getCurDate());
                addBrandInfo.setCreateTime(DateUtil.getCurDate());
                userBrandInfoMapper.addUserBrandInfo(addBrandInfo);
            } else {
                //如果品牌为无效状态，则进行修改
                int effectiveStatus = Optional.ofNullable(brandStatusInfo.getEffectiveStatus()).orElse(0);
                if (effectiveStatus == 0) {
                    UserBrandInfo updateBrandInfo = new UserBrandInfo();
                    updateBrandInfo.setId(brandStatusInfo.getId());
                    updateBrandInfo.setEffectiveStatus(1);
                    updateBrandInfo.setModifyTime(new Date());
                    userBrandInfoMapper.updateUserBrandInfo(updateBrandInfo);
                }

            }
        }

        processUserBrandSelectStatus(userId);

        return 0;
    }

    @Override
    public int unSubBrandInfo(Integer userId, Integer brandId) {

        UserBrandInfo updateBrandInfo = new UserBrandInfo();
        updateBrandInfo.setBrandId(brandId);
        updateBrandInfo.setUserId(userId);
        updateBrandInfo.setEffectiveStatus(0);
        updateBrandInfo.setBrandStatus(0);
        userBrandInfoMapper.updUserBrandSubStatus(updateBrandInfo);

        processUserBrandSelectStatus(userId);

        return  0;
    }

    @Override
    public int subBrandInfo(Integer userId, Integer brandId) {
        //查询用户对当前品牌的设置情况
//        UserBrandInfo queryInfo = new UserBrandInfo();
//        queryInfo.setUserId(userId);
//        queryInfo.setBrandId(brandId);
//        UserBrandInfo brandStatusInfo = userBrandInfoMapper.queryUserBrandStatusInfo(queryInfo);

        List<String> brandIdsArr = Lists.newArrayList();
        brandIdsArr.add(brandId.toString());
        // 通过品牌ID查询品牌绑定的品牌id信息
        String brandBindingIds = brandInfoMapper.queryBrandBindingIdsByBrandId(brandId);
        if(StringUtils.isNotBlank(brandBindingIds)) {
            String[] brandBindings = brandBindingIds.split(",");

            for (String brandBindingId : brandBindings) {
                //if (!Arrays.asList(branIds).contains(brandBindingId)){
                brandIdsArr.add(brandBindingId);
                //}
            }
        }

        //如果不存在，则直接添加
        Integer index=0;
        for (String brandIdInfo : brandIdsArr) {
            Integer brandIdInt = Integer.valueOf(brandIdInfo);

            //查询用户对当前品牌的设置情况
            UserBrandInfo queryInfo = new UserBrandInfo();
            queryInfo.setUserId(userId);
            queryInfo.setBrandId(brandIdInt);
            UserBrandInfo brandStatusInfo = userBrandInfoMapper.queryUserBrandStatusInfo(queryInfo);

            //如果不存在，则直接添加
            if (brandStatusInfo == null) {
                UserBrandInfo addBrandInfo = new UserBrandInfo();
                addBrandInfo.setBrandId(brandIdInt);
                addBrandInfo.setUserId(userId);
                addBrandInfo.setBrandStatus(0);
                addBrandInfo.setEffectiveStatus(1);
                addBrandInfo.setCreateTime(new Date());
                addBrandInfo.setIndexNum(index);
                userBrandInfoMapper.addUserBrandInfo(addBrandInfo);
            } else {
                //如果品牌为无效状态，则进行修改
                int effectiveStatus = Optional.ofNullable(brandStatusInfo.getEffectiveStatus()).orElse(0);
                if (effectiveStatus == 0) {
                    UserBrandInfo updateBrandInfo = new UserBrandInfo();
                    updateBrandInfo.setId(brandStatusInfo.getId());
                    updateBrandInfo.setEffectiveStatus(1);
                    //updateBrandInfo.setCreateTime(new Date());
                    updateBrandInfo.setModifyTime(new Date());
                    updateBrandInfo.setIndexNum(index);
                    userBrandInfoMapper.updateUserBrandInfo(updateBrandInfo);
                }

            }
            index++;
        }

        processUserBrandSelectStatus(userId);

        return 0;
    }

    @Override
    public BrandInfo getUserSelectBrandInfo(Integer userId) {
        return userBrandInfoMapper.queryUserSelectBrandInfo(userId);
    }

    @Override
    public int getBrandSubCount(Integer brandId) {
        return userBrandInfoMapper.queryBrandSubCount(brandId);
    }

    /**
     * 处理微站品牌选中信息
     * @param userId
     */
    private void processUserBrandSelectStatus(Integer userId) {

        List<UserBrandCombinedInfo> userBrandCombinedInfoList = userBrandInfoMapper.queryUserBrandInfo(userId);

        if (CollectionUtils.isNotEmpty(userBrandCombinedInfoList)) {

            boolean matchResult = userBrandCombinedInfoList.stream().parallel().noneMatch(info -> Optional.ofNullable(info.getBrandStatus()).orElse(0).intValue() == 1);

            //如果找不到选中的品牌信息，则设置第一个为选中
            if (matchResult) {

                UserBrandInfo userBrandInfo = new UserBrandInfo();
                userBrandInfo.setUserId(userId);
                Integer brandId = userBrandCombinedInfoList.get(0).getBrandId();
                userBrandInfo.setBrandId(brandId);
                userBrandInfoMapper.updateUserSpecialBrandStatus(userBrandInfo);

            }

            BrandInfo selectBrandInfo = userBrandInfoMapper.queryUserSelectBrandInfo(userId);

            if (selectBrandInfo != null && selectBrandInfo.getId() != null) {
                addUserPlatformCommodityAsyncTask.addUserPlatformCommodityAsyncTask(userId, selectBrandInfo.getId());
            }
        }

    }

    /**
     * 用户更新品牌海报
     * @param userBrandInfo
     * @return
     */
    @Override
    public int uploadUserBandPosterImg(UserBrandInfo userBrandInfo) {
        return userBrandInfoMapper.uploadUserBandPosterImg(userBrandInfo);
    }

    @Override
    public int copyRefererBrand(Integer userId, Integer referer) {
        return userBrandInfoMapper.copyRefererBrand(userId, referer);
    }

    /**
     * 用户查询品牌海报
     * @param userBrandInfo
     * @return
     */
    @Override
    public UserBrandInfo queryUserBandPosterImg(UserBrandInfo userBrandInfo) {
        return userBrandInfoMapper.queryUserBandPosterImg(userBrandInfo);
    }

    /**
     * 获取用户品牌海报信息
     * @param userId
     * @return
     */
    @Override
    public List<UserBrandInfo> queryUserBandPosterImgInfoList(Integer userId) {
        return userBrandInfoMapper.queryUserBandPosterImgInfoList(userId);
    }

    /**
     * 获取用户品牌海报信息
     *
     */
    @Override
    public boolean setDefaultBrand(String springProfilesActive,Integer finalUserId,int type) {
        String brandNames = "";
        boolean setUserType = false;
        boolean setUserBrand = false;

        //如果是 淘小铺，默认设置 淘小铺品牌 20200215
        if (springProfilesActive != null && springProfilesActive.equals("prodzx1")) {
            brandNames = "装修";
            // 20200702 yl 装修1 默认关注的品牌
            addUserBrandInfo(finalUserId, 24441, 1, 1, DateUtil.getCurDate(), 0);
            addUserBrandInfo(finalUserId, 25846, 0, 1, DateUtil.getCurDate(), 1);
            addUserBrandInfo(finalUserId, 25848, 0, 1, DateUtil.getCurDate(), 2);
            addUserBrandInfo(finalUserId, 25847, 0, 1, DateUtil.getCurDate(), 3);

            iUserRelateArticleTypeInfoService.recordUserRelateArticleTypeInfo(finalUserId, "1");
            setUserBrand = true;
            setUserType = true;
        } else if (springProfilesActive != null && (springProfilesActive.equals("prodhyxt") || springProfilesActive.equals("prodhysck"))) { //护眼学堂
            brandNames = "护眼";

            addUserBrandInfo(finalUserId, 15509, 1, 1, DateUtil.getCurDate(), 0);//护眼知识
            addUserBrandInfo(finalUserId, 30684, 0, 1, DateUtil.getCurDate(), 1);//防近视知识
            setUserBrand = true;
        } else if (springProfilesActive != null && (springProfilesActive.equals("prodshjj") || springProfilesActive.equals("prodshsck"))) { //私护之家
            brandNames = "私护";

            addUserBrandInfo(finalUserId, 14182, 1, 1, DateUtil.getCurDate(), 0);//私护
            addUserBrandInfo(finalUserId, 14227, 0, 1, DateUtil.getCurDate(), 1);//美业
            setUserBrand = true;
        } else if (springProfilesActive != null && springProfilesActive.equals("prodbkwz")) { //鼻康微站
            brandNames = "鼻腔康复";
            addUserBrandInfo(finalUserId, 17115, 1, 1, DateUtil.getCurDate(), 0);//鼻腔康复
            setUserBrand = true;
        } else if (springProfilesActive != null && springProfilesActive.equals("proddsk")) {//多锁客
            subBrandInfo(finalUserId, 28769);//好货内购
            setUserBrand = true;
        } else if (springProfilesActive != null && springProfilesActive.equals("prodszts")) {//飞天推手 改成 爆单推手 改成 淘淘特助手 改成 长生露科技
            brandNames = "长生露";
            subBrandInfo(finalUserId, 27949);//27949	长生露
            setUserBrand = true;
        } else if (springProfilesActive != null && springProfilesActive.equals("prodttsck")) {//淘特素材库
            brandNames = "淘特";
            subBrandInfo(finalUserId, 48630);//淘特
            setUserBrand = true;
        } else if (springProfilesActive != null && springProfilesActive.equals("prodmyds")) {//美牙大使
            brandNames = "美牙";
            subBrandInfo(finalUserId, 39433);//美牙
            setUserBrand = true;

        } else if (springProfilesActive != null && springProfilesActive.equals("prodssxt")) {//塑身学堂
            brandNames = "塑身";
            subBrandInfo(finalUserId, 10879);//减肥瘦身
            setUserBrand = true;

        } else if (springProfilesActive != null && springProfilesActive.equals("prodgjhkpt")) {//共建获客平台
            brandNames = "双特";

            addUserBrandInfo(finalUserId, 41018, 1, 1, DateUtil.getCurDate(), 0);//共建集体
            addUserBrandInfo(finalUserId, 35456, 0, 1, DateUtil.getCurDate(), 1);//科技双特
            addUserBrandInfo(finalUserId, 27235, 0, 1, DateUtil.getCurDate(), 2);//聚多荣创
            addUserBrandInfo(finalUserId, 10840, 0, 1, DateUtil.getCurDate(), 3);//高佣联盟
            addUserBrandInfo(finalUserId, 52232, 0, 1, DateUtil.getCurDate(), 4);//黑卡优选

            iUserRelateArticleTypeInfoService.recordUserRelateArticleTypeInfo(finalUserId, "1,4,24");//支付 、健康、正能量
            setUserType = true;

            setUserBrand = true;

        } else if (springProfilesActive != null && springProfilesActive.equals("back_zkt")) {//金友
            brandNames = "信贷";

            addUserBrandInfo(finalUserId, 10832, 1, 1, DateUtil.getCurDate(), 0);//信用卡
            addUserBrandInfo(finalUserId, 36237, 0, 1, DateUtil.getCurDate(), 1);//贷款
            addUserBrandInfo(finalUserId, 36238, 0, 1, DateUtil.getCurDate(), 2);//征信
            addUserBrandInfo(finalUserId, 36239, 0, 1, DateUtil.getCurDate(), 3);//逾期

            iUserRelateArticleTypeInfoService.recordUserRelateArticleTypeInfo(finalUserId, "16");//保险
            setUserType = true;
            setUserBrand = true;
        } else if (springProfilesActive != null && (springProfilesActive.equals("prodxscja") || springProfilesActive.equals("prodbdxzs"))) {//小神吹
            brandNames = "虫草硒牡蛎钙";

            subBrandInfo(finalUserId, 33220);//虫草硒牡蛎钙
            setUserBrand = true;
        } else if (springProfilesActive != null && springProfilesActive.equals("prodkshf")) {//抗衰学堂
            brandNames = "抗衰学堂";

            subBrandInfo(finalUserId, 51891);//抗衰学堂
            setUserBrand = true;
        } else if (springProfilesActive != null && springProfilesActive.equals("prodjzyxt")) {//金钻云学堂
            subBrandInfo(finalUserId, 56);//完美
            iUserRelateArticleTypeInfoService.recordUserRelateArticleTypeInfo(finalUserId, "50,51,52,53,54,55");
            setUserType = true;
            setUserBrand = true;
        }

        redisCacheUtil.setCacheObject("subUserIdBrandNamese:" + finalUserId, brandNames, 60000);

        if (!setUserBrand && type == 1) {//经过上边的专业号 如果也没有 设置到 品牌，就找用户 看的第一个文章的品牌
            setUserOneBrandId(springProfilesActive, finalUserId);
        }

        return setUserType;
    }

    private boolean setUserOneBrandId(String springProfilesActive,Integer userId){
        LookArticleInfo oneArticle= iLookArticleInfoService.getUserOneBrandId(springProfilesActive,userId);
        if(oneArticle!=null && oneArticle.getArticleBrandId()>0){
            subBrandInfo(userId, oneArticle.getArticleBrandId());
            return true;
        }
        return false;
    }

}
